package com.design.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.design.common.JsonResult;
import com.design.sys.entity.User;
import com.design.sys.service.IUserService;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yang
 * @since 2023-06-09
 */

@Api(value="User Controller")
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation(value="获取所有用户")
    @GetMapping("/all")
    public JsonResult<List<User>> getAllUser(){
        List<User> userlist = userService.getAllUsers();
        return JsonResult.success(userlist);
    }
    @ApiOperation(value="登录接口")
    @PostMapping("/login")
    public JsonResult<Map<String,Object>> login(@RequestBody @ApiParam(value = "User") User user){
        Map<String, Object> loginData = userService.login(user);
        if (loginData != null){
            return JsonResult.success(loginData);
        }
        return JsonResult.fail("用户名或密码错误");
    }

    @GetMapping("/info")
    public JsonResult<?> getUserInfo(@Param("token") String token){
        Map<String,Object> data=userService.getUserInfo(token);
        if (data!=null){
            return JsonResult.success(data);
        }
        return JsonResult.fail("登录信息无效，请重新登录");
    }


    @PostMapping("/logout")
    public JsonResult<?> logout(@RequestHeader("X-Token") String token){
        userService.logout(token);
        return JsonResult.success("注销成功");
    }

    @GetMapping("/getlist")
    public JsonResult<?> getUserListPage(@RequestParam(value = "username", required = false) String username,
                                     @RequestParam(value = "phone", required = false) String phone,
                                     @RequestParam("pageNo") @Min(value = 1, message = "页码必须大于等于1") Long pageNo,
                                     @RequestParam("pageSize") Long pageSize) {

        //验证手机号格式
        if (!StringUtils.isNullOrEmpty(phone) && !phone.matches("^1[3-9]\\d{9}$")){
            return JsonResult.fail("请输入正确的手机号");
        }
        // 页码校验
        if (pageNo < 1) {
            return JsonResult.fail("页码必须大于0");
        }
        //解决查询项为空不能点击无法查询的bug
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper();
        wrapper.eq(!StringUtils.isNullOrEmpty(username), User::getUsername, username);
        wrapper.eq(!StringUtils.isNullOrEmpty(phone), User::getPhone, phone);
        //按照userId降序排序
        wrapper.orderByDesc(User::getId);
        //计算总页数
        Page<User> page = new Page<>(pageNo, pageSize);
        userService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return JsonResult.success(data);
    }
    @PostMapping
    public JsonResult<?> addUser(@RequestBody User user){
        //密码MD5加密存入数据库
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.addUser(user);
        return JsonResult.success("新增用户成功");
    }
    @PutMapping()
    public JsonResult<?> updateUser(@RequestBody User user){
        user.setPassword(null);
        userService.updateUser(user);
        return JsonResult.success("修改用户成功");
    }
    @GetMapping("/{id}")
    public JsonResult<?> getUserById(@PathVariable("id") Integer id){
        User user = userService.getUserById(id);
        return JsonResult.success(user);
    }

    @DeleteMapping("/{id}")
    public JsonResult<?> deleteUserById(@PathVariable("id") Integer id){
        //物理删除
        userService.deleteUserById(id);
        return JsonResult.success("删除用户成功");
    }




}
